var module = {};
var scriptObj = {};
var cssObj = {};
var classPool = [];
var sharePool = {};
var easyMe = {};
var exceptionConfig;
var loginConfig;
var isRedirectedLogin = false;
var jsCacheCheckPool = {};
var eventFlux = new EventEmitter();
replaceAll = function(str, s1,s2) {
    return str.replace(new RegExp(s1,"gm"),s2);
}
function isInLoginConfig() {
    for(var index  = 0; index < loginConfig.length; index++) {
        if(location.href.indexOf("/" + loginConfig[index]) > -1) {
            return true;
        }
    }
    return false;
}
easyMe.components = {};
easyMe.import = function(componentPath) {
    return easyMe.components[componentPath];
}
easyMe.httpResponseInterceptor = function(res) {
    if(!exceptionConfig) {
        exceptionConfig = $.ajax({
            url: "common/exceptionConfig.json",
            type: "GET",
            async: false
        }).responseText;
        exceptionConfig = JSON.parse(exceptionConfig);
    }
    if(!loginConfig) {
        loginConfig = $.ajax({
            url: "common/loginConfig.json",
            type: "GET",
            async: false
        }).responseText;
        loginConfig = JSON.parse(loginConfig).data;
    }
    for(var code in exceptionConfig) {
        if(res[code]) {
            for(var val in exceptionConfig[code]) {
                if(val == res[code]) {
                    var gotoUrl = exceptionConfig[code][val];
                    if(window.location.href.indexOf("/login") == -1 && res.isLogin && val == "401") {
                        if(!isRedirectedLogin) {
                            isRedirectedLogin = true;
                            location.href = "/login?errorCode=401&redirectUrl=" + encodeURIComponent(location.pathname + location.search);
                        }
                    } else if(val != "401" && val != '403') {
                        location.href = gotoUrl;
                    }
                    break;
                }
            }
        }
    }
    return res;
}
easyMe.getQueryString = function(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
easyMe.useJs = function(jsArray) {
    for(var index = 0; index < jsArray.length; index++) {
        var scriptId = hex_md5(jsArray[index]);
        if($("#" + scriptId).length == 0) {
            $.ajax({
                "type": "GET",
                "url": "combineAssetsAction/?params=" + jsArray[index],
                "dataType": "text",
                "async": false,
                "cache": true,
                "success": function(result) {
                    var scriptEle = document.createElement("script");
                    scriptEle.innerHTML = result;
                    scriptEle.id = scriptId;
                    $("head")[0].appendChild(scriptEle);
                }
            });
        }
    }
}
window.use = function(pathArray, callback, async) {
    if(typeof async == "undefined") {
        async = true;
    }
    var componentArray = [];
    var headEle = $("head");
    var loadLength = 0;
    function request(url, callback) {
        $.ajax({
            "type": "GET",
            "url": url,
            "dataType": "text",
            "success": function(result) {
                store.set(url, {
                    md5: hex_md5(result),
                    content: result
                });
                callback(result);
            }
        });
    }
    function checkNew(path, url, callback) {
        var cacheMapActionUrl = "cacheMapAction/?url=" + url;
        if(jsCacheCheckPool != "false") {
            callback(JSON.parse(jsCacheCheckPool)[path]);
        } else {
            callback(false);
        }
    }
    function checkBatchNew(url, callback) {
        var cacheMapActionUrl = "cacheMapAction/?url=" + url;
        $.ajax({
            "type": "GET",
            "url": cacheMapActionUrl,
            "dataType": "text",
            "success": function(result) {
                callback(result);
            }
        });
    }
    function checkAllCacheIsNew(jsArray) {
        var assets= [];
        for(var index = 0; index < jsArray.length; index++) {
            if(jsArray[index].indexOf("/widget/") > -1) {
                assets.push(replaceAll(jsArray[index], ".js", ".css"));
            }
            assets.push(jsArray[index]);
        }
        var jsUrl = "";
        for(var index = 0; index < assets.length; index++) {
            var jsPath = assets[index].split("/");
            jsPath.splice(0, 1);
            jsPath = jsPath.join("/");
            var result = store.get(jsPath);//先从本地获取到源代码
            if(result) {
                jsUrl += jsPath + ";" + result.md5 + ",";
            }
        }
        if(jsUrl.lastIndexOf(",") == jsUrl.length - 1) {
            jsUrl = jsUrl.substring(0, jsUrl.length - 1);
        }
        checkBatchNew(jsUrl, function(checkList) {
            jsCacheCheckPool = checkList;
            startLoad();
        });
    }
    function getRemoteTpl(pathItems, callback) {
        var url = pathItems.join("/");
        var result = store.get(url);//先从本地获取到源代码
        if(!result) {//如果本地不存在
            request(url, callback);
        } else {//如果本地存在
            checkNew(url, url + "&md5=" + result.md5, function(isNew) {//检查是否为最新的
                if(isNew == true) {//如果是最新的
                    callback(result.content);
                } else {//如果不是最新的
                    request(url, callback);
                }
            });
        }
    }
    function insertCssToPage(cssPath) {
        cssPath = replaceAll(cssPath, ".js", ".css");
        var result = cssObj[cssPath];
        if(result && result.indexOf("server-load") == -1) {
            var styleEle = $("<style></style>");
            styleEle.html(result);
            headEle.append(styleEle);
        }
    }
    function insertScriptToPage() {
        for(var index = 0; index < pathArray.length; index++) {
            if(pathArray[index].indexOf("widget") != -1) {
                insertCssToPage(pathArray[index]);
            }
            var scriptHtml = scriptObj[pathArray[index]];
            //var scriptHtml = babel(scriptHtml).code;//将react代码编译成js原生代码
            var scriptEle = $(document.createElement("script"));//$("<script></script>");
            scriptEle.html(scriptHtml);
            headEle.append(scriptEle);
            componentArray.push(module.exports);
            easyMe.components[pathArray[index]] = module.exports;
            sharePool[pathArray[index]] = module.exports;
        }
        if(callback) {
            callback.apply(callback, componentArray);
        }
    }
    function loadExistComponent(path) {
        var time = setInterval(function () {
            if (sharePool[path]) {
                componentArray.push(sharePool[path]);
                if (componentArray.length == pathArray.length) {//装载完成
                    if(callback) {
                        callback.apply(callback, componentArray);
                    }
                }
                clearInterval(time);
            }
        }, 10);
    }
    function insertCodeToCom(jsText, eventName) {
        var componentDidMountPos = jsText.indexOf("componentDidMount");
        var reactClassPos = jsText.indexOf("React.createClass({");
        if(componentDidMountPos > -1) {
            var insertStartPos = jsText.indexOf("{", componentDidMountPos);
            var headJsText = jsText.substring(0, insertStartPos + 1);
            var footJsText = jsText.substring(insertStartPos + 1, jsText.length);
            jsText = headJsText + "\n\t\tvar self = this;\n\t\teventFlux.subscribe('" + eventName + "', function() {return self;});\n\t\t" + footJsText;
        }
        /*if(reactClassPos > -1) {
         var insertStartPos = reactClassPos + "React.createClass({".length;
         var headJsText = jsText.substring(0, insertStartPos);
         var footJsText = jsText.substring(insertStartPos, jsText.length);
         jsText = headJsText + "valueLinked: function(attr, id) {var self = this;var timer = null;if(!$('#' + id).isBind) {$('#' + id).isBind = true;var val = '';setInterval(function() {if($('#' + id).length > 0) {if(!timer) {timer = setInterval(function () {clearInterval(timer);$('#' + id).on('keyup', function () {val = $('#' + id).val();self.state.data[attr] = $('#' + id).val();}); }, 0);}}}, 0);}},\n\tapply: function() {\n\t\tthis.setState(this.state);\n\t}," + footJsText;
         }*/
        return jsText;
    }
    function dealCallbackResult(result, tplName, fileName, url) {
        result = insertCodeToCom(result, tplName + "_" + fileName + "_Event");
        scriptObj[url] = result;
        classPool.push(url);
        loadLength++;
        if(loadLength == pathArray.length) {
            insertScriptToPage();
        }
    }
    function startLoad() {
        var assets= [];
        for(var index = 0; index < pathArray.length; index++) {
            if(pathArray[index].indexOf("/widget/") > -1) {
                assets.push(replaceAll(pathArray[index], ".js", ".css"));
            }
        }
        assets = $.merge(assets, pathArray);
        for(var index = 0; index < assets.length; index++) {
            if(cssObj[assets[index]]) {
                continue;
            }
            if(classPool.indexOf(assets[index]) != -1) {
                loadExistComponent(assets[index]);
                continue;
            }
            (function(i) {
                var tplName = "";
                var fileName = "";
                var pathItems = assets[i].split("/");
                if(assets[i].indexOf("Service.js") != -1) {//解析service路径
                    tplName = assets[i].split("/")[2];
                    fileName = assets[i].split("/")[3].substring(0, assets[i].split("/")[3].indexOf(".js"));
                } else if(assets[i].indexOf("widget") != -1) {//解析widget路径
                    tplName = assets[i].split("/")[2];
                    fileName = assets[i].split("/")[3].substring(0, assets[i].split("/")[4].indexOf(".js"));
                } else if(assets[i].indexOf("public/common") > -1 || assets[i].indexOf("public/component") > -1) {
                    tplName = assets[i].split("/")[1];
                    fileName = assets[i].split("/")[2].substring(0, assets[i].split("/")[2].indexOf(".js"));
                } else {//解析组件路径
                    tplName = assets[i].split("/")[2];
                    fileName = assets[i].split("/")[3].substring(0, assets[i].split("/")[3].indexOf(".js"));
                }
                pathItems.splice(0, 1);
                getRemoteTpl(pathItems, function(result) {
                    if(assets[i].indexOf(".js") > -1) {
                        dealCallbackResult(result, tplName, fileName, assets[i]);
                    } else {
                        cssObj[assets[i]] = result;
                    }
                });
            })(index);
        }
    }
    checkAllCacheIsNew(pathArray);//批量检测js是否过期
}